package fans_group

import (
	"context"
	"longmen/server/config/global"
	"longmen/server/internal/rpc/tencentim/cache"
	chat2 "longmen/server/internal/rpc/tencentim/chat"
	"longmen/server/internal/rpc/tencentim/config"
	"longmen/server/internal/rpc/tencentim/imsdk"
	"longmen/server/internal/rpc/tencentim/utils"
	pb "longmen/server/pkg/protobuf"
)

type (
	fansGroup struct {
		req  *pb.CallbackReq
		ctx  context.Context
		user *chat2.ClientUser
	}
)

func newFansGroup(ctx context.Context, req *pb.CallbackReq) (*fansGroup, error) {
	user, err := chat2.GetUserByReq(req)
	if err != nil {
		global.Log.Errorf("user not login : %s", err.Error())
		_, _ = cache.SetClientBeforeLogin(req)
		user, err = chat2.GetUserByReq(req)
		if err != nil {
			return nil, err
		}
	}
	return &fansGroup{
		ctx:  ctx,
		req:  req,
		user: user,
	}, nil
}

func FansGroupHandler(ctx context.Context, req *pb.CallbackReq) (*pb.CallbackResp, error) {
	global.Log.Debugf("FansGroupHandler req:%v", req)
	instance, err := newFansGroup(ctx, req)
	if err != nil {
		global.Log.Errorf(" user err: %v", err)
		return utils.FailCodeResp(imsdk.TIM_ERROR_CODE_REJECT, "用户错误，请重新登录后重试"), nil
	}

	switch req.GetCallbackCommand() {

	case config.BeforeJoinRoom:
		// 加入房间，是否允许
		return instance.beforeJoinRoom()

	case config.RoomBeforeMsg:
		// 发言前过滤
		// 是否允许发言
		return instance.beforeMessageProcess()

	case config.RoomAfterMsg:
		// 写入历史记录
		return instance.afterMessageProcess()

	}
	return utils.CallbackOkResp("Ok"), nil
}
